<template>
  <div class="box">
    <div class="title">{{pageTitle}}</div>
    <section>
      <div class="section">
        <el-form :inline="true" ref="search_form" :model="searchForm" size="small">
          <el-form-item label="配送商" prop="type">
            <el-select v-model="searchForm.merchant_id" clearable filterable placeholder="选择配送商" style="width: 240px;">
              <el-option
                v-for="(item,index) in merchantData"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="模板类型" prop="type">
            <el-select v-model="searchForm.type" clearable placeholder="模板类型" style="width: 240px;">
              <el-option
                v-for="(item,index) in typeData"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="initList">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="tempList" style="width: 100%" size="mini" border>
        <el-table-column label="配送商" width="300">
          <template slot-scope="scope">
            <span>{{scope.row.merchant ?scope.row.merchant.title :'系统模版'}}</span>
          </template>
        </el-table-column>
        <el-table-column label="模板名称" prop="title" width="200"></el-table-column>
        <el-table-column label="模板类型">
          <template slot-scope="scope">
            <span>{{scope.row.typeName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="模板宽高">
          <template slot-scope="scope">
            <span>{{scope.row.width + ' x '+ scope.row.height}}</span>
          </template>
        </el-table-column>
        <el-table-column label="纸张大小">
          <template slot-scope="scope">
            <span>{{scope.row.pageWidth + 'mm x '+ scope.row.pageHeight+'mm'}}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" width="300">
          <template slot="header">
            <el-button size="mini" type="primary" @click="openCreate">添加</el-button>
          </template>
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleEdit(scope.$index, scope.row)">设计</el-button>
            <el-button type="primary" size="mini" @click="handlePreview(scope.$index, scope.row)">预览</el-button>
            <el-button type="primary" size="mini" @click="handleCopy(scope.row)">复制</el-button>
            <el-button
              v-if="scope.row.default !=1"
              type="danger"
              size="mini"
              @click="handleDelete(scope.$index, scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="添加模板" :visible.sync="visible" width="400px">
        <el-form ref="form" :model="form" size="small" :rules="rules" label-width="120px">
          <el-form-item label="配送商" prop="type">
            <el-select v-model="form.merchant_id" filterable placeholder="选择配送商" style="width: 240px;">
              <el-option
                v-for="(item,index) in merchantData"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="模板名称" prop="title">
            <el-input v-model="form.title" placeholder="模板名称"></el-input>
          </el-form-item>
          <el-form-item label="模板类型" prop="type">
            <el-select v-model="form.type" placeholder="模板类型" style="width: 240px;">
              <el-option
                v-for="(item,index) in typeData"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="模板宽度" prop="width">
            <el-input v-model="form.width" placeholder="模板宽度"></el-input>
          </el-form-item>
          <el-form-item label="模板高度" prop="height">
            <el-input v-model="form.height" placeholder="模板高度"></el-input>
          </el-form-item>
          <el-form-item label="纸张宽度(mm)" prop="pageWidth">
            <el-input v-model="form.pageWidth" placeholder="纸张宽度"></el-input>
          </el-form-item>
          <el-form-item label="纸张高度(mm)" prop="pageHeight">
            <el-input v-model="form.pageHeight" placeholder="纸张高度"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" @click="visible = false">取 消</el-button>
          <el-button type="primary" size="mini" @click="onSave">确 定</el-button>
        </div>
      </el-dialog>
    </section>
  </div>
</template>
<script>
  import {index, merchant, type, edit, del} from '../service/api'

  const defaultTemp = () => ({
    merchant_id: '',
    title: '',
    type: 1, // 模板类型 1:发货单;2:分拣单;3;配送单;4:入库单;5:出库单
    width: 750,
    height: 500,
    pageWidth: '',
    pageHeight: '',
    tempItems: [],
  })

  export default {
    data() {
      return {
        pageTitle: process.env.VUE_APP_NAME,
        merchant_id: 0,
        visible: false,
        value: {},
        tempList: [],
        form: defaultTemp(),
        rules: {
          title: {required: true, message: '请输入模板名称'},
          type: {required: true, message: '请选择模板类型'},
          width: {required: true, message: '请输入模板宽度'},
          height: {required: true, message: '请输入模板高度'},
          pageWidth: {required: true, message: '请输入纸张宽度'},
          pageHeight: {required: true, message: '请输入纸张高度'},
        },
        searchForm: {
          merchant_id: '',
          type: '',
        },
        printForm: {
          tempIndex: '',
          data: '',
        },
        merchantData: [],
        typeData: [],
      }
    },
    created() {
      this.initList();
      this.getTypeData();
      this.getMerchantData();
    },

    methods: {
      initList() {
        index(this.searchForm).then(res => {
          if (res.data.code == 200) {
            this.tempList = (res.data.data)
          }
        }).catch(err => {
          console.log('失败')
        })
      },
      //配送商类型
      getMerchantData() {
        merchant().then(res => {
          if (res.data.code == 200) {
            this.merchantData = res.data.data
          }
        }).catch(err => {
          console.log('失败')
        })
      },
      //模版类型
      getTypeData() {
        type().then(res => {
          if (res.data.code == 200) {
            this.typeData = res.data.data
          }
        }).catch(err => {
          console.log('失败')
        })
      },
      // 新增
      openCreate() {
        this.form = defaultTemp()
        this.visible = true
      },
      // 保存新增
      onSave() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            edit(this.form).then(res => {
              const data = res.data
              if (data.code == 200) {
                this.setSuccess(data)
                this.initList()
              } else {
                this.setError(data)
              }
            }).catch(err => {
              this.setError(data)
            })
            this.visible = false
          }
        })
      },
      // 删除
      handleDelete(index, row) {
        this.$confirm('确认删除该条数据吗？', '确认信息')
          .then((isPass) => {
            if (isPass) {
              del({id: row.id}).then(res => {
                const data = res.data
                if (data.code == 200) {
                  this.setSuccess(data)
                  this.initList()
                } else {
                  this.setError(data)
                }
              }).catch(err => {
                this.setError(data)
              })
            }
          }).catch()
      },
      // 预览
      handlePreview(index, row) {
        this.$lodop.previewTemp(row)
      },
      // 设计
      handleEdit(index, row) {
        this.$router.push({
          path: '/designer',
          query: {
            id: row.id,
          },
        })
      },
      //复制
      handleCopy(row) {
        if (this.searchForm.merchant_id <= 0) {
          return this.setError({message: '请先选择一个配送商'})
        }
        let copyTemp = JSON.parse(JSON.stringify(row))
        this.form = defaultTemp()
        this.form.merchant_id = this.searchForm.merchant_id
        this.form.title = copyTemp.title + '_copy'
        this.form.type = copyTemp.type
        this.form.width = copyTemp.width
        this.form.height = copyTemp.height
        this.form.pageWidth = copyTemp.pageWidth
        this.form.pageHeight = copyTemp.pageHeight
        this.form.tempItems = copyTemp.tempItems
        edit(this.form).then(res => {
          const data = res.data
          if (data.code == 200) {
            this.setSuccess(data)
            this.initList()
          } else {
            this.setError(data)
          }
        }).catch(err => {
          this.setError(data)
        })
      },
      setSuccess(data) {
        this.$message({
          showClose: true,
          message: data.message || '操作成功',
          type: 'success'
        });
      },
      setError(data) {
        this.$message({
          showClose: true,
          message: data.message || '操作失败',
          type: 'error'
        });
      },
      /**
       * 测试打印预览/直接打印
       * flag 1:打印预览，2：直接打印
       */
      printPreview(flag) {
        this.$refs.printForm.validate((valid) => {
          if (valid) {
            let printData
            try {
              printData = JSON.parse(this.printForm.data)
            } catch (err) {
              return this.$message('请输入正确格式的打印数据')
            }
            if (flag == 1) {
              this.$lodop.preview(this.tempList[this.printForm.tempIndex], printData)
            } else {
              this.$confirm('确认直接打印吗？', '确认信息')
                .then((isPass) => {
                  if (isPass) {
                    this.$lodop.print(this.tempList[this.printForm.tempIndex], printData)
                  }
                })
                .catch((err) => {
                  console.log(err)
                })
            }
          }
        })
      },
    },
  }
</script>
<style scoped>
  .box {
    margin: auto;
    padding: 10px 200px;
    font-family: Arial, Helvetica, sans-serif;
  }

  .title {
    text-align: center;
    font-size: 24px;
    color: #1890ff;
    margin: 20px;
    font-weight: bold;
  }

  .section {
    display: inline-block;
    font-size: 18px;
    color: #333333;
    padding: 10px 0;
  }
</style>
